package org.wingstudio.controller.admin;

import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.wingstudio.entity.*;
import org.wingstudio.service.*;
import org.wingstudio.util.AsposeUtil;
import org.wingstudio.util.CryptographyUtil;
import org.wingstudio.util.ResponseUtil;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统管理模块
 * Created by liao on 16-11-10.
 */

@Controller
@RequestMapping("/user/admin")
public class SystemAdminController {
    @Resource
    private NewsTypeService newsTypeService;
    @Resource
    private FileTypeService fileTypeService;
    @Resource
    private UserService userService;
    @Resource
    private StyleService styleService;
    @Resource
    private ScrollPictureService scrollPictureService;
    @Resource
    private LinkService linkService;
    @Resource
    private NewsService newsService;
    @Resource
    private PictureService pictureService;
    /**
     * 刷新系统缓存
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/refreshSystem")
    public String refreshSystem(HttpServletRequest request,HttpServletResponse response)
    throws Exception{
        ServletContext application= RequestContextUtils.getWebApplicationContext
                (request).getServletContext();
        List<NewsType> newsTypeList=newsTypeService.countList();
        List<FileType> fileTypeList=fileTypeService.countList();

        application.setAttribute("newsTypeList", newsTypeList);
        application.setAttribute("fileTypeList", fileTypeList);
        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 管理员注销登录
     * @return
     * @throws Exception
     */
    @RequestMapping("/logout")
    public String logout()throws Exception{
        SecurityUtils.getSubject().logout();
        return "redirect:/loginRedirect.jsp";
    }

    @RequestMapping("/modifyPassword")
    public String modifyPassword(String newPassword,HttpServletResponse response)
            throws Exception{
        System.out.println("test password:"+newPassword);
        User user=new User();
        user.setPassword(CryptographyUtil.md5(newPassword, "liaochuanhu"));
        Integer resultTotal=userService.update(user);
        JSONObject result=new JSONObject();
        if(resultTotal>0){
            result.put("success", true);
        }else{
            result.put("success", false);
        }
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("/color")
    public ModelAndView color()throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("user/admin/system/colorManage");
        return modelAndView;
    }

    @RequestMapping("/setColor")
    public String setColor(@RequestParam(value="id")String id,
                           HttpServletRequest request,
                           HttpServletResponse response)throws Exception{
        ServletContext application=RequestContextUtils.getWebApplicationContext(request).getServletContext();
        styleService.init();
        styleService.set(Integer.parseInt(id));
        if(Integer.parseInt(id)==1){
            application.setAttribute("color","red.css");
        }else if(Integer.parseInt(id)==2){
            application.setAttribute("color","black.css");
        }else if(Integer.parseInt(id)==3){
            application.setAttribute("color","brown.css");
        }
        List<Link> linkList=linkService.list();
        application.setAttribute("linkList",linkList);
        List<News> recentNews=newsService.getRecent();
        application.setAttribute("recentNews",recentNews);

        List<Picture> pictureList=pictureService.list();
        Picture p1=pictureList.get(0);
        Picture p2=pictureList.get(1);
        Picture p3=pictureList.get(2);
        Picture p4=pictureList.get(3);
        Picture p5=pictureList.get(4);


        application.setAttribute("p1",p1);
        application.setAttribute("p2",p2);
        application.setAttribute("p3",p3);
        application.setAttribute("p4",p4);
        application.setAttribute("p5",p5);

        JSONObject result=new JSONObject();
        result.put("success",true);
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("/picture")
    public ModelAndView setPicture()throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        List<ScrollPicture> scrollPictureList=scrollPictureService.list();
        modelAndView.addObject("scrollPictureList",scrollPictureList);
        modelAndView.setViewName("user/admin/system/pictureManage");
        return modelAndView;
    }

    @RequestMapping(value = "/updatePic", method = RequestMethod.POST)
    public String updatePic(HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestParam("file") MultipartFile file, ModelMap model,
                            ScrollPicture scrollPicture) throws Exception{

        String path = request.getSession().getServletContext().getRealPath("/static/scrollPic");
        String path2 = request.getSession().getServletContext().getRealPath("/static");
        String testFileName = file.getOriginalFilename();
        String prefix=testFileName.substring(testFileName.lastIndexOf(".")+1);
        String name=String.valueOf(Calendar.getInstance().getTimeInMillis());
        String imgName=name+"."+prefix;
        scrollPicture.setImgUrl(imgName);
        File targetFile = new File(path, imgName);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("imgUrl",imgName);
        map.put("id",scrollPicture.getId());
        scrollPictureService.update(map);
        // 保存原文件
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //model.addAttribute("fileUrl", request.getContextPath() + "/static/files/" + sourceName);
        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("/setting")
    public ModelAndView setting()throws Exception{
        ModelAndView modelAndView=new ModelAndView();

        modelAndView.setViewName("user/admin/system/userManage");
        return modelAndView;
    }

    @RequestMapping("/modify")
    public String modify(User user,HttpServletRequest request,HttpServletResponse response)
            throws Exception{

        CryptographyUtil cryptographyUtil=new CryptographyUtil();
        String password=request.getParameter("password");
        if(request.getParameter("userName")!=null){
            String userName=request.getParameter("userName");
            user.setUserName(userName);
        }
        User user1=userService.check( cryptographyUtil.md5(password,"liaochuanhu"));
        if(user1!=null){
            user.setPassword(cryptographyUtil.md5(request.getParameter("password1"),
                    "liaochuanhu"));
            userService.update(user);
            JSONObject result=new JSONObject();
            result.put("success",true);
            ResponseUtil.write(response, result);
        }else {
            JSONObject result=new JSONObject();
            result.put("success",false);
            ResponseUtil.write(response, result);
        }

        return null;
    }
}
